const express = require('express')
const router = express.Router()
// 导入题目数据模块
const topicModel = require('../../model/topicModel')
// 引入jwt token工具
const JwtUtil = require('../../utils/jwt')
const getCreateTime = require('../../utils/getCreateTime')
const config = require('../../config/default')
const HOSTURL = `${config.PROTOCOL}://${config.HOST}:${config.PORT}`
//上传图片的包
const multer = require('multer')
const { v4: uuidv4 } = require('uuid')
// 通过filename属性定制
const storage = multer.diskStorage({
    // 保存的路径
    destination: function (req, file, callback) {
        callback(null, 'public/upload/')
    },
    filename: function (req, file, callback) {
        // 将保存文件名设置为 字段名 + 时间戳，比如 logo-1478521468943
        let suffix = file.mimetype.split('/')[1]; //获取文件格式
        callback(null, file.fieldname + '-' + Date.now() + '.' + suffix);
    }
})
// 生成的图片放入uploads文件夹下
const upload = multer({ storage: storage })
// 1.0 添加题目（添加题目）
router.post('/add', upload.single('photo'), function (req, res) {
    // 请求需要进行token校验 
    let token = req.body.token
    let jwt = new JwtUtil(token)
    let result = jwt.verifyToken()
    let topic_id = uuidv4() || Math.random().toString().slice(2)
    // 接收前端的参数
    let topic_title = req.body.topic_title 
    let topic_text = req.body.topic_text
    let topic_create_time = getCreateTime.now()
    let topic_navigate = req.body.topic_navigate 
    let topic_author = req.body.topic_author 
    let topic_option = req.body.topic_option 
    let topic_answer = req.body.topic_answer 
    let topic_desc = req.body.topic_desc || '无解析。' 
    let topic_hot = 'normal'
    if (result == 'err') {
        res.send({
            code: -1,
            msg: '登录已过期,请重新登录'
        })
    } else {
        if (result.data) {
            let user_id = result.data;
            // 调用添加题目的方法
            // console.log({ topic_id,topic_title,topic_text,topic_create_time,user_id,topic_navigate,topic_option,topic_answer,topic_hot,topic_desc})
            topicModel.add(topic_id, topic_title, topic_text, topic_create_time, user_id, topic_navigate,topic_author,topic_option,topic_answer,topic_hot,topic_desc)
                .then(
                    data => {
                        res.send(data)
                    }
                )
                .catch(
                    err => {
                        res.send({ code: 500, msg: '服务器异常...', err })
                    }
                )
        }
    }
})

// 2.0 删除题目（删除题目）
router.post('/remove', function (req, res) {
    let token = req.body.token
    let topic_id = req.body.topic_id
    let jwt = new JwtUtil(token)
    let result = jwt.verifyToken()
    if (result == 'err') {
        res.send({
            code: -1,
            msg: '登录已过期,请重新登录'
        })
    }
    else {
        if (result.data) {
            let user_id = result.data
            // 调用删除题目的方法  
            topicModel.remove(topic_id)
                .then(
                    data => {
                        res.send(data)
                    }
                )
                .catch(
                    err => {
                        res.send({ code: 500, msg: '服务器异常...', err })
                    }
                )
        }
    }
})

// 3.0 获取题目列表接口（题目列表）
router.get('/list', function (req, res) {
    // 调用获取题目列表方法
    topicModel.list()
        .then(
            data => {
                res.send(data)
            }
        )
        .catch(
            err => {
                res.send({ code: 500, msg: '服务器异常...', err })
            }
        )
})

// 4.0 搜索题目接口（搜索题目）
router.get('/search', async (req, res) =>{
    let keyword = req.query.keyword;
    // console.log(keyword)
    // 多字段模糊查询
    // 调用搜索题目方法
    await  topicModel.search(keyword)
        .then(
            data => {
                res.send(data)
            }
        )
        .catch(
            err => {
                res.send({ code: 500, msg: '服务器异常...', err })
            }
        )
})

// 5.0 获取题目详情（题目详情）
router.get('/detail', function (req, res) {
    let topic_id = req.query.topic_id
    // 调用获取题目详情方法
    topicModel.detail(topic_id)
        .then(
            data => {
                res.send(data)
            }
        )
        .catch(
            err => {
                res.send({ code: 500, msg: '服务器异常...', err })
            }
        )

})

// 6.0 获取导航分类信息
router.get('/navigate', function (req, res) {
    let topic_navigate = req.query.topic_navigate
    // 调用获取题目详情方法
    topicModel.getNavigate(topic_navigate)
        .then(
            data => {
                res.send(data)
            }
        )
        .catch(
            err => {
                res.send({ code: 500, msg: '服务器异常...', err })
            }
        )
})

// 7.0 获取指定分页题目列表
router.get('/items', async (req, res) =>{
    const page_num = req.query.page_num //当前的页码
    const page_size = req.query.page_size //当前页的数量
    // 调用获取分页题目列表
    topicModel.items(page_num,page_size)
        .then(
            data => {
                res.send(data)
            }
        )
        .catch(
            err => {
                res.send({ code: 500, msg: '服务器异常...', err })
            }
        )
})

//8.0  统计题目数量
router.get('/all', async (req, res) => {
    // 调用获取分页题目列表
    await topicModel.all()
        .then(
            data => {
                res.send(data)
            }
        )
        .catch(
            err => {
                res.send({ code: 500, msg: '服务器异常...', err })
            }
        )
})

// 9.0 更新题目
router.post('/update', upload.single('photo'),  async (req, res) => {
    let topic_id = req.body.topic_id
    let topic_title = req.body.topic_title
    let topic_text = req.body.topic_text
    let topic_create_time = getCreateTime.now()
    let topic_author = req.body.topic_author
    let topic_navigate = req.body.topic_navigate
    let topic_option = req.body.topic_option 
    let topic_answer = req.body.topic_answer 
    // console.log({topic_id, topic_title, topic_text, topic_create_time, topic_author, topic_navigate, topic_option,topic_answer})
    // 调用获取文章详情方法
    await topicModel.update(topic_id, topic_title, topic_text, topic_create_time, topic_author, topic_navigate, topic_option,topic_answer)
        .then(
            data => {
                res.send(data)
            }
        )
        .catch(
            err => {
                res.send({ code: 500, msg: '服务器异常...', err })
            }
        )
})

// 10.0 题目推荐热门
router.get('/hot', function (req, res) {
    let topic_id = req.query.topic_id
    let topic_hot = req.query.topic_hot
    // 调用搜索题目方法
    topicModel.hot(topic_id,topic_hot)
        .then(
            data => {
                res.send(data)
            }
        )
        .catch(
            err => {
                res.send({ code: 500, msg: '服务器异常...', err })
            }
        )
})

// 11.0 热门列表
router.get('/hot_list', function (req, res) {
    // 调用搜索题目方法
    topicModel.hot_list()
        .then(
            data => {
                res.send(data)
            }
        )
        .catch(
            err => {
                res.send({ code: 500, msg: '服务器异常...', err })
            }
        )
})
module.exports = router;